/**
 * @file 工单操作-改定金
 * @author yangjiangming <449654337@qq.com>
 * @date 2018-12-10 20:13:16
 */
layui.define(['layer', 'form', 'list_modify_common', '$http'], function (exports) {
    var $ = layui.$;
    var form = layui.form;
    var opCommonUtils = layui.list_modify_common;

    var $http = layui.$http;

    Number.prototype.div = function (arg) {
        var t1 = 0, t2 = 0, r1, r2;
        try {
            t1 = this.toString().split(".")[1].length
        } catch (e) {
        }
        try {
            t2 = arg.toString().split(".")[1].length
        } catch (e) {
        }
        with (Math) {
            r1 = Number(this.toString().replace(".", ""));
            r2 = Number(arg.toString().replace(".", ""));
            return (r1 / r2) * pow(10, t2 - t1);
        }
    };

    /**
     * 提示信息
     * @param str {string}
     */
    function toast(str) {
        layer.msg(str);
        return
    }

    /**
     * 分转元
     * @param num
     * @returns {*}
     * @constructor
     */

    function Fen2Yuan(numstr) {
        var num = Number(numstr);
        return (num.div(100)).toFixed(2);
    }

    /**
     * 元转分
     * @param numstr
     * @returns {string}
     * @constructor
     */
    function Yuan2Fen(numstr) {
        var num = Number(numstr)
        return (num * 100).toFixed(0);
    }

    /**
     * 判断是否是正整数且最多小数点后两位;
     * @param val {number/string} 字符串或数字
     * @returns {boolean} 返回是否是数字
     */
    function isNumber(val) {
        var reg = /^[0-9]+([.]{1}[0-9]{1,2})?$/;//正整数到小数点后两位
        return reg.test(val);
    };


    /**
     * 获取input框数值
     * @param ele{dom}
     * @returns {jQuery}
     */
    function getValue(ele) {
        var val = $(ele).val() || $(ele).text();
        if (val && isNumber(val)) {
            val = Number(val);
            return val;
        }
        return 0
    }


    /**
     * 根据工程师收款金额判断是否开启上门费
     * @param gathering {number} 工程师收款金额
     */
    function isGathering(gathering) {
        if (gathering <= 30 && updatePriceVO.clean != 2) {
            $(".d-visit").prop("disabled", false);
            form.render();
        } else {
            $(".d-visit").prop("disabled", true).prop("checked", false);
            form.render();
        }
    }

    /**
     * 基本验证
     */
    function verify(val) {
        if (!isNumber(val) || val < 0) {
            return "请输入大于0的数且最多两位小数";
        }
        if (val > 100000000) {
            return "不能大于1亿";
        }

        var original = Yuan2Fen($(".d-original").val());//订单金额
        var deposit = Yuan2Fen($('.d-earnest').val());//定金
        var preferential = Yuan2Fen($('.d-discounts-item').html());
        var advance = Yuan2Fen($('.d-advances').html());
        if (advance == 'NaN') {
            advance = 0;
        }

        var gathering = Fen2Yuan(original - deposit - preferential - advance);//工程师收款金额
        if (gathering < 0) {
            return "有立减优惠或有预付款或有定金时原价不能为0";
        }
    }


    /**
     * 刷新工程师收款金额
     */
    function theGathering() {
        var original = Yuan2Fen($(".d-original").val());//订单金额
        var deposit = Yuan2Fen($('.d-earnest').val());//定金
        var preferential = Yuan2Fen($('.d-discounts-item').html());
        var advance = Yuan2Fen($('.d-advances').html());
        if (advance == 'NaN') {
            advance = 0;
        }

        var gathering = Fen2Yuan(original - deposit - preferential - advance);//工程师收款金额
        $(".d-gathering").html(gathering);
    }

    /**
     * 原价输入框
     */
    function listenOriginal() {
        $(".d-original").on("change", function (event) {
            var index;
            var val = event.currentTarget.value;
            var result = verify(val);
            if (result != null) {
                layer.msg(result);
                $('.d-original').val('');
            }
            $.ajax({
                url: "/work/modify/find/discount.action",
                type: "POST",
                data: JSON.stringify({
                    orderId: orderId,
                    workId: workId,
                    originalAmount: (val * 100).toString(),
                    equtityId: updatePriceVO.equtityId
                }),
                contentType: 'application/json;charset=utf-8',
                beforeSend: function () {
                    index = layer.load();
                    $('#submit-btn').attr('disabled', true).addClass('layui-btn-disabled');
                },
                success: function (data) {
                    if (data.statusBool) {
                        renderOffer(data.data.discountVOList);
                        //刷新工程师收款金额
                        theGathering();
                        processHomeAmount();
                    }
                },
                complete: function () {
                    layer.close(index);
                    $('#submit-btn').attr('disabled', false).removeClass('layui-btn-disabled');
                }

            });
        })
    }

    /**
     * 渲染优惠项目
     * @param data
     */
    function renderOffer(discountVOList, isAMember) {
        $('#offer-item').empty()
        var total = 0
        var totalMember = 0

        var html = '';
        for (var i = 0; i < discountVOList.length; i++) {
            var discountVOListElement = discountVOList[i];

            html += '<div class="layui-inline">\n' +
                '                    <div class="layui-form-label">' + discountVOListElement.categName + '</div>\n' +
                '                    <div class="layui-inline" style="line-height: 34px;">\n' +
                '                        <span>' + Fen2Yuan(discountVOListElement.amount) + '</span>\n' +
                '                        -<span>' + discountVOListElement.typeName + '</span></div>\n' +
                '                </div>';

            // 判断是否是会员单且是会员优惠
            if (updatePriceVO.member == 2 && discountVOListElement.categ == 23) {
                totalMember ++;

            }
            $('#offer-item').append(html);
            total += discountVOListElement.amount;
        }
        
        if (updatePriceVO.member == 2 && totalMember == 0) {
            // language=HTML
            html = '<div class="layui-inline">\n' +
                '                    <div class="layui-form-label">会员优惠</div>\n' +
                '                    <div class="layui-inline" style="line-height: 34px;color: red">无,原价大于剩余金额.不可使用会员优惠</div>\n' +
                '                </div>';
            $('#offer-item').html(html);
        }

        $('#totalOffer').html(Fen2Yuan(total));
    }


    /**
     * 定价输入框
     */
    function listenEarnest() {
        $(".d-earnest").on("input", function (event) {
            var val = event.currentTarget.value;
            val = Number(val);
            var original = $(".d-original").val();//订单金额
            var yh = getValue(".d-discounts-item");//优惠
            var advance = getValue(".d-advances");//预收款
            var maxEarnest = (original - yh - advance).toFixed(2);//最大定金
            var gathering = (original - val - yh - advance).toFixed(2);//工程师收款金额

            if (!isNumber(val)) {
                toast("请输入正数且最多两位小数");
                $(".d-earnest").val("");
                return
            }
            if (!original) {
                toast("请先填写原价");
                $(".d-earnest").val("");
                return
            }

            if (+original == 0) {
                toast("原价为0时定金不可填写");
                $(".d-earnest").val("");
                return
            }

            if (val && val < 0) {
                toast("请输入正数");
                $(".d-earnest").val("");
                return
            }

            if (val > maxEarnest) {
                toast("定金需小于" + maxEarnest + "元");
                $(".d-earnest").val("");
                return
            }

            theGathering();
            processHomeAmount();
        })
    }

    function processHomeAmount(){
        var val = $(".d-earnest").val();
        var original = $(".d-original").val();//订单金额
        var yh = getValue(".d-discounts-item");//优惠
        var advance = getValue(".d-advances");//预收款
        var gathering = (original - val - yh - advance).toFixed(2);//工程师收款金额
        isGathering(gathering);
    }

    /**
     * 初始化页面
     */
    function initPage() {
        form.verify({
            "user-number": function (val) {
                var result = verify(val);
                if (result != null) {
                    return result;
                }
            }
        });
        //渲染工程师收款金额 订单金额 - 优惠总额 - 预收款 - 定金
        $('.d-gathering').text(Fen2Yuan(updatePriceVO.masterAmount));
        $('.d-earnest').val(Fen2Yuan(updatePriceVO.depositAmount));

        //渲染原价
        if (updatePriceVO.originalAmount) {
            $('.d-original').val(Fen2Yuan(updatePriceVO.originalAmount));
        }
        //渲染优惠项
        var isAMember = updatePriceVO.member == 2;

        renderOffer(updatePriceVO.discountVOList, isAMember);
        //渲染预付款
        $('.d-advances').text(Fen2Yuan(updatePriceVO.prepayAmount));
    }

    /**
     * 获取原因
     * @returns {string}
     */
    function getReason() {
        var reason = '';
        $("#reason input:checked").each(function (i) {
            reason += this.value;
            reason += ','
        });
        reason += $('textarea').val();
        return reason;
    }

    /**
     * 初始化页面事件
     */
    function initEvent() {

        //扩展除法
        Number.prototype.div = function (arg) {
            var t1 = 0, t2 = 0, r1, r2;
            try {
                t1 = this.toString().split(".")[1].length
            } catch (e) {
            }
            try {
                t2 = arg.toString().split(".")[1].length
            } catch (e) {
            }
            with (Math) {
                r1 = Number(this.toString().replace(".", ""));
                r2 = Number(arg.toString().replace(".", ""));
                return (r1 / r2) * pow(10, t2 - t1);
            }
        };


        //保存
        form.on("submit()", function (data) {
            data.field['discountAmount'] = Yuan2Fen($('#totalOffer').html());
            //定金
            data.field['depositAmount'] = Yuan2Fen(data.field['depositAmount']);
            //订单金额
            data.field['originalAmount'] = Yuan2Fen(data.field['originalAmount']);
            data.field['prepayAmount'] = Yuan2Fen($('.d-advances').html() == undefined ? 0 : $('.d-advances').html());
            data.field['masterAmount'] = Yuan2Fen($('.d-gathering').html());
            data.field['onlyVisit'] = data.field['visit'] == 2 ? 2 : 1;
            data.field['orderId'] = orderId;
            data.field['workId'] = workId;
            data.field['operatorRemark'] = getReason();
            delete data.field['visit']
            if (+data.field['depositAmount'] > +data.field['originalAmount']) {
                toast('定金必须小于原价');
                window.document.getElementById('depositAmount').focus();
                return false;
            }

            var url = '/work/modify/save/price.action';
            $http.lockSave(url, data.field, data.elem).then(function () {
                layer.msg('操作成功', { icon: 1, time: 1000 }, function () {
                    opCommonUtils.goOperateHome();
                });
            }, (msg) => {
                layer.msg(msg);
            });
            return false;
        });
        //验证输入的数字

        //监听原价输入框
        listenOriginal();
        //监听定金输入框
        listenEarnest();
    }

    // 程序入口
    function init() {

        // 初始化页面
        initPage();

        // 初始化事件
        initEvent();

    }


    // 初始化
    init();

    exports('oms_work_modify_price');
});
